package com.gnerv.battle.boot.framework.core.tools.command;

import com.gnerv.battle.boot.framework.core.exception.BusinessException;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @author Gnerv LiGen
 */
@Slf4j
public class SftpTools extends AbstractCommandTools {

    private SftpTools() {
    }

    public static ExecResult upload(File src, File dst, String username, String password, String host, int port) {
        ExecResult execResult = new ExecResult();
        Session session = getSession(username, password, host, port);
        Channel channel;
        try {
            channel = session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            throw new BusinessException(e.getMessage());
        }
        ChannelSftp channelSftp = (ChannelSftp) channel;
        try {
            channelSftp.cd(dst.getParent());
            channelSftp.put(src.getAbsolutePath(), dst.getName());
        } catch (SftpException e) {
            throw new BusinessException("get channel failed", e);
        }
        channelSftp.exit();
        channelSftp.disconnect();
        session.disconnect();
        log.info(execResult.toString());
        return execResult;
    }

    public static ExecResult download(File src, File dst, String username, String password, String host, int port) {
        ExecResult execResult = new ExecResult();
        Session session = getSession(username, password, host, port);
        Channel channel;
        try {
            channel = session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            throw new BusinessException(e.getMessage());
        }
        ChannelSftp channelSftp = (ChannelSftp) channel;
        try {
            channelSftp.cd(dst.getParent());
            channelSftp.get(src.getAbsolutePath(), new FileOutputStream(dst));
        } catch (SftpException e) {
            throw new BusinessException("get channel failed", e);
        } catch (FileNotFoundException e) {
            throw new BusinessException(e.getMessage());
        }
        channelSftp.exit();
        channelSftp.disconnect();
        session.disconnect();
        log.info(execResult.toString());
        return execResult;
    }




}
